const { app, BrowserWindow, ipcMain, Tray, nativeImage } = require('electron')
const path = require('path')
const { release } = require('os')

// 禁用 Windows 7 的 GPU 加速
if (release().startsWith('6.1')) app.disableHardwareAcceleration()

// 设置应用名称
app.setName('Electron-Vue3-Vite')

// 只允许单实例运行
if (!app.requestSingleInstanceLock()) {
  app.quit()
  process.exit(0)
}

// 定义全局变量
let win = null
const preload = path.join(__dirname, 'preload.js')

async function createWindow() {
  win = new BrowserWindow({
    title: 'Zephyr',
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    webPreferences: {
      preload,
      nodeIntegration: false,
      contextIsolation: true,
    },
    icon: path.join(__dirname, '../src/assets/logos/logo.png'),
    autoHideMenuBar: false,
    frame: false,
    titleBarStyle: 'hidden',  // 对于 macOS
  })

  // 加载页面
  if (app.isPackaged) {
    win.loadFile(path.join(__dirname, '../dist/index.html'))
  } else {
    // 开发模式
    win.loadURL(process.env.VITE_DEV_SERVER_URL)
    // 打开开发者工具
    win.webContents.openDevTools()
  }

    // 系统托盘配置
  const trayIcon = nativeImage.createFromPath(path.join(__dirname, '../../src/assets/logos/logo.png'))
  const tray = new Tray(trayIcon.resize({ width: 16, height: 16 }))
  tray.setToolTip('Zephyr')

  // 窗口事件监听
  win.on('ready-to-show', () => {
    win.show()
  })
}

// 应用准备就绪时创建窗口
app.whenReady().then(createWindow)

// 所有窗口关闭时退出应用，macOS除外
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// macOS 点击 dock 图标时重新创建窗口
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// 处理来自渲染进程的消息
ipcMain.handle('app-version', () => {
  return app.getVersion()
})

// 窗口控制事件
ipcMain.on('window-minimize', () => {
  if (win) win.minimize()
})

ipcMain.on('window-maximize', () => {
  if (win) {
    if (win.isMaximized()) {
      win.unmaximize()
    } else {
      win.maximize()
    }
  }
})

ipcMain.on('window-close', () => {
  if (win) win.close()
})
